"""
Web监控界面主应用
"""
import os
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_login import LoginManager, login_required, current_user, login_user, logout_user
from werkzeug.security import check_password_hash, generate_password_hash
from sqlalchemy.orm import scoped_session, sessionmaker

from modules.models.base import engine
from modules.web.admin import setup_admin
from modules.web.dashboard import register_dashboards
from modules.web.auth import User, LoginForm, RegisterForm
from config.settings import SECRET_KEY

# 创建Flask应用
app = Flask(__name__, 
            template_folder=os.path.join(os.path.dirname(__file__), 'templates'),
            static_folder=os.path.join(os.path.dirname(__file__), 'static'))
app.config['SECRET_KEY'] = SECRET_KEY
app.config['SQLALCHEMY_DATABASE_URI'] = str(engine.url)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'

# 设置登录管理器
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

# 创建数据库会话
Session = scoped_session(sessionmaker(bind=engine))

# 注册Admin管理界面
admin = setup_admin(app)

# 注册Dash仪表盘
register_dashboards(app)


@login_manager.user_loader
def load_user(user_id):
    """加载用户"""
    session = Session()
    try:
        return session.query(User).get(int(user_id))
    finally:
        session.close()


@app.route('/')
def index():
    """首页"""
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    form = LoginForm()
    if form.validate_on_submit():
        session = Session()
        try:
            user = session.query(User).filter_by(username=form.username.data).first()
            if user and check_password_hash(user.password_hash, form.password.data):
                login_user(user, remember=form.remember.data)
                next_page = request.args.get('next')
                return redirect(next_page or url_for('index'))
            flash('用户名或密码错误，请重试。', 'danger')
        finally:
            session.close()
    return render_template('login.html', form=form)


@app.route('/logout')
@login_required
def logout():
    """退出登录"""
    logout_user()
    flash('您已成功退出登录。', 'success')
    return redirect(url_for('index'))


@app.route('/register', methods=['GET', 'POST'])
def register():
    """注册页面"""
    form = RegisterForm()
    if form.validate_on_submit():
        session = Session()
        try:
            # 检查用户名是否已存在
            existing_user = session.query(User).filter_by(username=form.username.data).first()
            if existing_user:
                flash('用户名已存在，请尝试其他用户名。', 'danger')
                return render_template('register.html', form=form)
            
            # 创建新用户
            new_user = User(
                username=form.username.data,
                email=form.email.data,
                password_hash=generate_password_hash(form.password.data)
            )
            session.add(new_user)
            session.commit()
            flash('注册成功！请登录。', 'success')
            return redirect(url_for('login'))
        finally:
            session.close()
    return render_template('register.html', form=form)


@app.route('/dashboard')
@login_required
def dashboard():
    """仪表盘页面"""
    return render_template('dashboard.html')


@app.route('/tasks')
@login_required
def tasks():
    """任务监控页面"""
    return render_template('tasks.html')


@app.route('/data')
@login_required
def data():
    """数据管理页面"""
    return render_template('data.html')


@app.errorhandler(404)
def not_found_error(error):
    """404错误处理"""
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return render_template('500.html'), 500


def create_app():
    """创建并返回Flask应用"""
    return app


if __name__ == '__main__':
    """直接运行此文件时执行"""
    app.run(debug=True, host='0.0.0.0', port=5000)